package com.shenjinzheng.movie_ticket_app.utils


sealed class Result<out T> {
    data class Success<out T>(val data: T) : Result<T>()
    data class Failure(val error: Throwable) : Result<Nothing>()
    object Loading : Result<Nothing>()

    companion object {
        fun <T> success(data: T): Result<T> = Success(data)
        fun <T> failure(exception: Throwable): Result<T> = Failure(exception)
        fun <T> loading(): Result<T> = Loading
    }

    // 便捷方法
    fun isSuccess(): Boolean = this is Success
    fun isLoading(): Boolean = this is Loading
    fun isFailure(): Boolean = this is Failure

    fun getOrNull(): T? = (this as? Success<T>)?.data
    fun exceptionOrNull(): Throwable? = (this as? Failure)?.error
    // 在 Result.kt 文件中添加这些扩展函数
    fun <T> Result<T>.onSuccess(action: (T) -> Unit): Result<T> {
        if (this is Result.Success) action(this.data)
        return this
    }

    fun <T> Result<T>.onFailure(action: (Throwable) -> Unit): Result<T> {
        if (this is Result.Failure) action(this.error)
        return this
    }

}
